<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
	<link rel="stylesheet" href="./bootstrap.css">
	<script src="./vue-2.4.0.js"></script>
</head>

<body>
	<div id="app">
		<cmt-box @post-comment="loadComments"></cmt-box>
		<ul class="list-group">
			<li class="list-group-item" v-for="item in list" :key="item.id">
				<span class="badge">评论人:{{item.name}}</span>
				{{item.content}}
			</li>
		</ul>
	</div>

	<template id="tmpl">
		<div>
			<div class="form-group">
				<label>评论人:</label>
					<input type="text" class="form-control" v-model="name">
				
			</div>
			<div class="form-group">
				<label>评论内容:</label>
					<textarea class="form-control" v-model="content" @keyup.enter.prevent="postComment"></textarea>
			</div>
			<div class="form-group">
					<input type="button"  value="发表评论"  class="btn btn-primary" @click="postComment"/>
			</div>
		</div>
	</template>
	<script>
		//组件
		var commentBox = {
			data() {
				return {
					name: "",
					content: ""
				}
			},
			template: "#tmpl",
			methods: {
				postComment() {
					var comment ={id:Date.now(),name:this.name,content:this.content}
					var list = JSON.parse(localStorage.getItem('cmts') || '[]')
          			list.unshift(comment)
					localStorage.setItem('cmts',JSON.stringify(list))
					this.name = this.content =''
					this.$emit('post-comment')
				}
			}
		}

		new Vue({
			el: "#app",
			data: {
				list: [{
						id: Date.now(),
						name: '李白',
						content: '天生我材必有用'
					},
					{
						id: Date.now(),
						name: '江小白',
						content: '劝君更尽一杯酒'
					},
					{
						id: Date.now(),
						name: '小马',
						content: '我姓马， 风吹草低见牛羊的马'
					},
				]
			},
			created () {
				this.loadComments()	
			},
			methods: {
				loadComments(){// 从本地的 localStorage 中，加载评论列表
					this.list = JSON.parse(localStorage.getItem('cmts') || '[]')
				}
			},
			components: {
				//注册组件	
				'cmt-box': commentBox
			}
		})
	</script>
</body>

</html>